﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Windows.Forms;

namespace Reticle
{
    public static class CDKeyManager
    {

        public static List<string> LoadCDKeys(string product)
        {
            XDocument doc = XDocument.Load(Application.StartupPath + @"\files\config.xml");

            // STAR/SEXP keys are the same thing
            switch (product)
            {
                case "STAR":
                case "SEXP":
                    product = "STAR";
                    break;
            }

            var ElementsList = doc.Element("Config").Element("CDKeys").Descendants(product).Descendants("cdkey")
                         .Select(x => x.Value)
                         .ToList();

            return ElementsList;
        }

        public static void SaveCDKeys(List<string> cdkeys, string product)
        {
            XDocument doc = XDocument.Load(Application.StartupPath + @"\files\config.xml");

            // STAR/SEXP keys are the same thing
            switch (product)
            {
                case "STAR":
                case "SEXP":
                    product = "STAR";
                    break;
            }

            // Remove all previous cdkeys to add the new list (old keys are not deleted)
            try
            {
                doc.Element("Config").Element("CDKeys").Element(product).RemoveAll();
            }
            catch (Exception) { }

            foreach (string key in cdkeys)
            {
                XElement elem = new XElement("cdkey", key);
                //doc.Element("CDKeys").Element(product).Add(elem);
                doc.Element("Config").Element("CDKeys").Element(product).Add(elem);
            }

            doc.Save(Application.StartupPath + @"\files\config.xml");
        }
    }
}
